package com.onluy.frameworkcloud.tools;

public class AsciiUtil {
	
	
	 /**
     * 字符串转换为Ascii
     * @param value
     * @return
     */
    public static String stringToAscii(String value)  
    {  
        StringBuffer sbu = new StringBuffer();  
        char[] chars = value.toCharArray();   
        sbu.append("\\");
        for (int i = 0; i < chars.length; i++) {  
            if(i != chars.length - 1)  
            {  
                sbu.append(Integer.parseInt(String.valueOf((int)chars[i]))).append("\\"); 
            }  
            else {  
                sbu.append((int)chars[i]);  
            }  
        }  
        return ascii10ToHex16(sbu.toString());  

    }
	 
    /**
     * Ascii转换为字符串
     * @param value
     * @return
     */
    public static String asciiToString(String value)
    {   
    	value = ascii16ToAscii10(value);
        StringBuffer sbu = new StringBuffer();
        String[] chars = value.split("\\\\");
        for (int i = 1; i < chars.length; i++) {
            sbu.append((char) Integer.parseInt(chars[i]));
        }
        return sbu.toString();
    }
    
    
    /**
     * 十进制转十六进制
     * @param value
     * @return
     */
    private static String ascii10ToHex16(String value){
    	StringBuffer sbu = new StringBuffer();
    	sbu.append("\\");
        String[] chars = value.split("\\\\");
        for (int i = 1; i < chars.length; i++) {
        	 if(i != chars.length - 1)  
             {  
        		 String str = String.valueOf(Integer.toHexString(Integer.parseInt(chars[i])));
                 sbu.append(str).append("\\");
             }  
             else {  
            	 String str = String.valueOf(Integer.toHexString(Integer.parseInt(chars[i])));
                 sbu.append(str);
             }  
        	
        }
        return sbu.toString();
    }
    
    /**
     * 十六进制转十进制
     * @param value
     * @return
     */
    private static String ascii16ToAscii10(String value){
    	StringBuffer sbu = new StringBuffer();
    	sbu.append("\\");
        String[] chars = value.split("\\\\");
        for (int i = 1; i < chars.length; i++) {
        	 if(i != chars.length - 1)  
             {  
        		 String str = String.valueOf(Integer.parseInt(chars[i],16));
                 sbu.append(str).append("\\");
             }  
             else {  
            	 String str = String.valueOf(Integer.parseInt(chars[i],16));
                 sbu.append(str);
             }  
        }
        return sbu.toString();
    }
	 
}
